//
//  HomeViewController.m
//  busRoute
//
//  Created by 物恋网 on 16/11/15.
//  Copyright © 2016年 wlw. All rights reserved.
//

#import "HomeViewController.h"
#import "UIViewController+SCSliderMenu.h"
#import <UIKit/UIKit.h>
#import <MAMapKit/MAMapKit.h>
#import "CustomAnnotationView.h"
#import "ZLBusListRequest.h"
#import "MMAPointAnnotation.h"
#import "BusListRes.h"
#import "BusModel.h"
@interface HomeViewController ()<MAMapViewDelegate>
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapLocationManager*locationManager;
@property (nonatomic, strong) CLLocation *currentLocation;
@property (nonatomic, strong) NSMutableArray *dataSource;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavgationTitle:@"车调宝"];
    [self setRightNavgationBtnWithImage:@"nav_search"];
    [self setLeftNavgationBtnWithImage:@"nav_search"];
    ///初始化地图
    _mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    _mapView.delegate = self;
    //不显示罗盘
    _mapView.showsCompass = NO;
    // 地图SDK定位服务
    _mapView.showsUserLocation = YES; //YES 为打开定位，NO为关闭定位
   // [_mapView setUserTrackingMode: MAUserTrackingModeFollow animated:YES]; //地图跟着位置移动
    
    [_mapView setZoomLevel:16.1 animated:YES];
 
    
   
    
    ///把地图添加至view
    [self.view addSubview:_mapView];
   
    
    self.locationManager  = [[AMapLocationManager alloc] init];
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =5;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 5;
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
    __weak HomeViewController *wself = self;
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        NSLog(@"location:%@", location);
        
        if (regeocode)
        {
            NSLog(@"reGeocode:%@", regeocode);
            
         
            
            
            wself.currentLocation = location;
            wself.mapView.centerCoordinate = location.coordinate;
            
            CLLocationCoordinate2D leftTopLoc = [wself.mapView convertPoint:CGPointMake(0, 0) toCoordinateFromView:wself.mapView];
            CLLocationCoordinate2D rightBottomLoc = [wself.mapView convertPoint:CGPointMake(CGRectGetMaxX(wself.mapView.frame), CGRectGetMaxY(wself.mapView.frame)) toCoordinateFromView:wself.mapView];
            ZLBusListRequest *request =  [[ZLBusListRequest alloc] initWithModelClass:[BusListRes class] completeRequestBlock:^(id sender, NSString *msg, NSError *error) {
                if (error) {
                    [self.view makeToast:msg];
                    return;
                }
                self.dataSource = [NSMutableArray arrayWithArray:[(BusListRes*)sender data]];
                [self filterData];
            }];
            request.type = @(0);
            request.lng_wn = @(leftTopLoc.longitude);
            request.lat_wn = @(leftTopLoc.latitude);
            request.lng_es = @(rightBottomLoc.longitude);
            request.lat_es = @(rightBottomLoc.latitude);
            request.com_id = COMPANY_ID;
            request.user_id = USER_ID;
            request.user_type = USER_TYPE;
            ZLRequestOperationManager *manager = [[ZLRequestOperationManager alloc] init];
            [manager performWithRequest:request View:self.view];
        }
    }];

//    MMAPointAnnotation *pointAnnotation = [[MMAPointAnnotation alloc] init];
//    pointAnnotation.coordinate = CLLocationCoordinate2DMake(39.989631, 116.481018);
//    pointAnnotation.title = @"方恒国际";
//    pointAnnotation.subtitle = @"阜通东大街6号";
//    pointAnnotation.busyState = [NSString stringWithFormat:@"%@",@"N"];
//    [_mapView addAnnotation:pointAnnotation];
//    
//    MMAPointAnnotation *pointAnnotation1 = [[MMAPointAnnotation alloc] init];
//    pointAnnotation1.coordinate = CLLocationCoordinate2DMake(39.989631, 116.531018);
//    pointAnnotation1.title = @"方恒国际";
//    pointAnnotation1.subtitle = @"阜通东大街6号玩动物";
//    pointAnnotation1.busyState = [NSString stringWithFormat:@"%@",@"Y"];
//    [_mapView addAnnotation:pointAnnotation1];

    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    self.mapView.mapType = MAMapTypeStandard;
}
-(void)OnClickLeft
{
   
     [self.sliderMenuViewController showLeftMenuViewController];
}

-(void)OnClickRight{
    [self pushCanvas:@"WlwSearchController" withArgument:nil];
}


- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MMAPointAnnotation class]])
    {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        // annotationView.image = [UIImage imageNamed:@"icon_fm"];
        if ([[(MMAPointAnnotation *)annotation busyState] isEqualToString:@"1"]) {
             annotationView.image = [UIImage imageNamed:@"icon_fm"];
        }else{
             annotationView.image = [UIImage imageNamed:@"icon_kx"];
        }
       
        // 设置为NO，用以调用自定义的calloutView
        annotationView.canShowCallout = NO;
       
        
        // 设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -18);
        __weak HomeViewController *wself =self;
        [annotationView setBusSelectedBlock:^(id sender) {
            [wself requestDetail:sender];
        }];
        return annotationView;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    MMAPointAnnotation* data =   [view annotation];
    if ([data isKindOfClass:[MAUserLocation class]]) {
        return;
    }
    if ([data.busyState isEqualToString:@"1"]) {
        view.image = [UIImage imageNamed:@"icon_fm_pre"];
    }else{
        view.image = [UIImage imageNamed:@"icon_kx_pre"];
    }
}

/*!
 @brief 当取消选中一个annotation views时调用此接口
 @param mapView 地图View
 @param view 取消选中的annotationView
 */
- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view
{
    MMAPointAnnotation* data =   [view annotation];
    if ([data isKindOfClass:[MAUserLocation class]]) {
        return;
    }
    if ([data.busyState isEqualToString:@"1"]) {
        view.image = [UIImage imageNamed:@"icon_fm"];
    }else{
        view.image = [UIImage imageNamed:@"icon_kx"];
    }
}

-(void)requestDetail:(MMAPointAnnotation *)data
{
    //请求详细地址
    SDKLOG(@"eeeeee");
}

-(void)filterData
{
    for (int i = 0; i < self.dataSource.count; i++) {
        BusModel *data = [self.dataSource objectAtIndex:i];
        MMAPointAnnotation *pointAnnotation = [[MMAPointAnnotation alloc] init];
        pointAnnotation.coordinate = CLLocationCoordinate2DMake([data.lat floatValue], [data.lng floatValue]);
        pointAnnotation.subtitle = data.address;
        pointAnnotation.busyState = [NSString stringWithFormat:@"%@",data.busy];
        pointAnnotation.busId = [NSString stringWithFormat:@"%@",data.id];
        [_mapView addAnnotation:pointAnnotation];
    }
    
}

- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    CLLocationCoordinate2D leftTopLoc = [self.mapView convertPoint:CGPointMake(0, 0) toCoordinateFromView:self.mapView];
    CLLocationCoordinate2D rightBottomLoc = [self.mapView convertPoint:CGPointMake(CGRectGetMaxX(self.mapView.frame), CGRectGetMaxY(self.mapView.frame)) toCoordinateFromView:self.mapView];
    ZLBusListRequest *request =  [[ZLBusListRequest alloc] initWithModelClass:[BusListRes class] completeRequestBlock:^(id sender, NSString *msg, NSError *error) {
        if (error) {
            [self.view makeToast:msg];
            return;
        }
        self.dataSource = [NSMutableArray arrayWithArray:[(BusListRes*)sender data]];
        [self filterData];
    }];
    request.type = @(0);
    request.lng_wn = @(leftTopLoc.longitude);
    request.lat_wn = @(leftTopLoc.latitude);
    request.lng_es = @(rightBottomLoc.longitude);
    request.lat_es = @(rightBottomLoc.latitude);
    request.com_id = COMPANY_ID;
    request.user_id = USER_ID;
    request.user_type = USER_TYPE;
    ZLRequestOperationManager *manager = [[ZLRequestOperationManager alloc] init];
    [manager performWithRequest:request View:self.view];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
